/*
 Copyright 2009 Vova Shcherban (Shchvova)

 This file is part of JUTW.

 JUTW is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 JUTW is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with JUTW.  If not, see http://www.gnu.org/licenses/.
*/
package shchvova.jutw;

import umputun.jutw.utils.logging.ULogger;
import winterwell.json.JSONException;
import winterwell.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Vova Shcherban
 * This simple class for expanding short URL in text;
 * All work could be done by UrlExpander static fucntion
 * (Currently works only with "byt.ly" service)
 */
public class UrlExpander {
	private static final ULogger log = ULogger.getLogger();
	final private static String BIT_LY_BASE = "http://bit.ly/";
	final private static String BIT_LY_REGEXP = "(http://bit.ly/\\w([\\w]*))";

	/**
	 * Returns text with replaced short URLs. Currently replace only one url.
	 * @param textWithUrl shorten URL. f.e. "http://bit.ly/15Cmgo"
	 * @return text with replaced short URLs to expanded URL
	 */
	public static String Expand(String textWithUrl){
		//find all bit.ly links
		Matcher matcher = Pattern.compile(BIT_LY_REGEXP).matcher(textWithUrl);
		List<String> links = new LinkedList<String>();
		while(matcher.find())
		{
			links.add(textWithUrl.substring(matcher.start(), matcher.end()));
		}

		String ret = textWithUrl;
		for(String link : links){
			ret = ret.replace(link, ExpandOnlyUrl(link));
		}

		return ret;
	}



	/**
	 * Function to internal use. Expands pure short URL
	 * @param input short URL
	 * @return
	 */
	@SuppressWarnings("unchecked")
	protected static String ExpandOnlyUrl(String input){
		String ret=input;
		if(input.startsWith(BIT_LY_BASE)){
			try {
				URL url = new URL("http://api.bit.ly/expand?version=2.0.1&shortUrl="+input+"&login=shchvova&apiKey=R_3df95226a7767eb71ae1f4547c59d699");
				URLConnection connection = url.openConnection();
				connection.connect();
				BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
				StringBuilder bitlyAnswer = new StringBuilder();
				int c=0;
				while ((c = reader.read()) != -1) {
					bitlyAnswer.append((char) c);
				}
				JSONObject ansObj = new JSONObject(bitlyAnswer.toString());
				if(ansObj.getString("statusCode").compareToIgnoreCase("OK")==0){
					JSONObject resultObj = ansObj.getJSONObject("results");
					Iterator<String> bitlyIdIterator = (Iterator<String>)resultObj.keys();
					if(bitlyIdIterator.hasNext()){
						String bitlyId = (String) bitlyIdIterator.next();
						JSONObject bitlyIdObj = resultObj.getJSONObject(bitlyId);
						String longUrl = bitlyIdObj.getString("longUrl");
						ret = ret.replace("http://bit.ly/" + bitlyId, longUrl);
					}else
					{
						log.warning("Unable to expand short link. Not found. Ignoring.");
					}
				}else
				{
					log.warning("Unable to expand short link. Incorrect link status "+ansObj.getString("statusCode")+". Ignoring.");
				}
				reader.close();

			} catch (MalformedURLException e) {
				log.warning("Unable to expand short link. Bit.ly API error. Ignoring.");
			} catch (IOException e) {
				log.warning("Unable to expand short link. Bit.ly answer reading error. Ignoring.");
			} catch (JSONException e) {
				log.warning("Unable to expand short link. Bit.ly API Unknown answer. Ignoring.");
			}
			finally{
			}
		}
		return ret;
	}

}
